package physics.contactListeners
{
	import Box2D.Collision.b2Manifold;
	import Box2D.Common.Math.b2Vec2;
	import Box2D.Dynamics.b2ContactImpulse;
	import Box2D.Dynamics.b2ContactListener;
	import Box2D.Dynamics.Contacts.b2Contact;
	import gameObjects.GameObject;
	/**
	 * ...
	 * @author Leong Shi Yun
	 */
	public class ContactListener extends b2ContactListener
	{
		/* private const/var */
		private var m_vHandlers:Vector.<IContactListener> = null;
		
		/* public functions */
		public function ContactListener()
		{
			m_vHandlers = new Vector.<IContactListener>();
		}
		
		public function registerHandler(handler:IContactListener):void
		{
			if (m_vHandlers) m_vHandlers.push(handler);
		}
		
		/**
		 * called when two fixtures begin to touch
		 */
		override public function BeginContact(contact:b2Contact):void
		{
			for each(var contactHandler:IContactListener in m_vHandlers)
			{
				if (contactHandler) contactHandler.BeginContact(contact);
			}
		}
		
		/**
		 * Called when two fixtures cease to touch
		 */
		override public function EndContact(contact:b2Contact):void
		{
			for each(var contactHandler:IContactListener in m_vHandlers)
			{
				if (contactHandler) contactHandler.EndContact(contact);
			}
		}
		
		/**
		 * This is called to inspect a contact before it goes into the solver.
		 */
		override public function PreSolve(contact:b2Contact, oldManifold:b2Manifold):void
		{
			for each(var contactHandler:IContactListener in m_vHandlers)
			{
				if (contactHandler) contactHandler.PreSolve(contact, oldManifold);
			}
		}
		
		/**
		 * Useful for checking the impulse of collisons
		 */
		override public function PostSolve(contact:b2Contact, impulse:b2ContactImpulse):void
		{
			for each(var contactHandler:IContactListener in m_vHandlers)
			{
				if (contactHandler) contactHandler.PostSolve(contact, impulse);
			}
		}
		
		public function Destroy():void
		{
			for each(var contactHandler:IContactListener in m_vHandlers)
			{
				if (contactHandler) contactHandler = null;
			}
			
			m_vHandlers = null;
		}
	}

}
